package com.xiangwushuo.framework.service

import android.app.*
import android.content.Intent
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import com.xiangwushuo.framework.R
import com.xiangwushuo.framework.activity.main.MainActivity

/**
 * Copyright (C), 2019-2020
 * FileName: DaemonService
 * Author: Kevin
 * Date: 2020/3/12 15:38
 * Description: 守护进程 service
 * History:
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */
class DaemonService: Service() {

    companion object {

        private const val NOTIFICATION_CHANNEL_ID = "chongwa"
        private const val NOTIFICATION_CHANNEL_NAME = "chongwapeiwan"

        /**
         * 启动 守护进程 service
         */
        fun startDaemonService(application: Application) {
            val intent = Intent(application, DaemonService::class.java)
            if (Build.VERSION.SDK_INT >= 26) {
                application.startForegroundService(intent)
            } else {
                application.startService(intent)
            }
        }
    }

    override fun onCreate() {
        super.onCreate()

        // 设置前台
        setForeground()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return START_NOT_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    /**
     * 设置前台
     */
    private fun setForeground() {
//        val  builder = NotificationCompat.Builder(this, "notification_id")
//        builder.setSmallIcon(R.mipmap.ic_app_icon)
//        builder.setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_app_icon))

        val notificationManager = getSystemService(NOTIFICATION_SERVICE) as? NotificationManager ?: return

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { //只在Android O之上需要渠道
            val notificationChannel = NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW)
            // 如果这里用IMPORTANCE_NOENE就需要在系统的设置里面开启渠道，
            // 通知才能正常弹出
            notificationManager.createNotificationChannel(notificationChannel)
        }
        val builder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)

        val requestCode = 1
        val flags = PendingIntent.FLAG_UPDATE_CURRENT
        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(this, requestCode, intent, flags)

        builder.setSmallIcon(R.mipmap.ic_app_icon)
            .setContentTitle("冲蛙陪玩")
            .setContentText("冲蛙正在运行...")
            .setTicker("冲蛙正在运行...")
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setContentIntent(pendingIntent)

        val notification = builder.build()
        notification.flags = Notification.FLAG_AUTO_CANCEL

        // 设置前台
        startForeground(999, notification)
    }
}